<?php

namespace app\admin\model;
use think\Model;
use think\Db;

class OrganizationModel extends Model
{
    protected $name = 'organization';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
  
    /**
     * 根据搜索条件获取所有的用户数量
     * @param $where
     */
    public function getAllOrganizations($where)
    {
        return $this->where($where)->select();
    }
    /**
     * 根据搜索条件获取单位列表信息
     */
    public function getOrganizationsByWhere($map, $Nowpage, $limits)
    {
        return $this->field('think_organization.*')
            ->where($map)->page($Nowpage, $limits)->order('id desc')->select();
    }
    /**
     * 插入管理员信息
     * @param $param
     */
    public function insertOrganization($param)
    {
        try{
            $result = $this->save($param);
            if(false === $result){            
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
               return ['code' => 1, 'data' => '', 'msg' => '添加单位成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }

    /**
     * 编辑管理员信息
     * @param $param
     */
    public function editOrganization($param)
    {
        try{
            $result =  $this->save($param, ['id' => $param['id']]);
            if(false === $result){            
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑单位成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }


    /**
     * 根据管理员id获取角色信息
     * @param $id
     */
    public function getOneOrganization($id)
    {
        return $this->where('id', $id)->find();
    }


    /**
     * 删除管理员
     * @param $id
     */
    public function delOrganization($id)
    {
        try{

            $this->where('id', $id)->delete();
            Db::name('auth_group_access')->where('uid', $id)->delete();
            return ['code' => 1, 'data' => '', 'msg' => '删除单位成功'];

        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }
}